package com.t.bricks.bussiness.service.recharge.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.t.bricks.bussiness.db.dao.recharge.RechargeDao;
import com.t.bricks.bussiness.db.entity.recharge.Recharge;
import com.t.bricks.bussiness.db.entity.recharge.base.CustomerAccountBase;
import com.t.bricks.bussiness.db.entity.recharge.base.TallyBase;
import com.t.bricks.bussiness.service.recharge.RechargeService;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.model.Page;
import com.t.bricks.utils.function.data.IntegerUtil;
import com.t.bricks.utils.function.data.MoneyUtil;
import com.t.bricks.utils.spring.ModuleUtil;

/**
 * 充值管理'Recharge表'基本业务操作类接口实现
 * @author HuangXinBian
 * @DateTime 2022年07月14日 15:06:11
 */
@Service
public class RechargeServiceImpl implements RechargeService {

	@Autowired
	private RechargeDao rechargeDao;
	
	/**
	 * 创建sRecordKey用的干扰串
	 */
	@Value("${app.record.key.jam:123456}")
	private String recordKeyJam;
	
	/**
	 * 标记删除
	 * @Param uId
	 * @Param iVersion
	 * @Param sRecordKey
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity signDel(String uId, Integer iVersion, String sRecordKey) {
		if (null == uId || "".equals(uId.trim())) {
			return MsgEmity.err(8001, "记录编号缺失");
		}
		
		if (null == iVersion || iVersion.intValue() < 0) {
			return MsgEmity.err(8002, "记录版本号必须大于0");
		}
		
		if (null == sRecordKey || "".equals(sRecordKey.trim())) {
			return MsgEmity.err(8003, "记录验证密钥缺失");
		}
		
		MsgEmity me = rechargeDao.findById(uId);
		if (!me.isSuccess()) {
			return me;
		}
		
		String sLoginUserId = ModuleUtil.currentLoginUserId();
		
		Recharge recharge = me.getData();
		if (!sLoginUserId.equals(recharge.getsCreator()) && !"00000000/00000001".contains(sLoginUserId)) {
			return MsgEmity.err(8004, "当前用户无权删除此记录");
		}
		
		if (sRecordKey.equals(recharge.getsRecordKey())) {
			return MsgEmity.err(8005, "记录验证密钥错误");
		}
		
		if (iVersion.equals(recharge.getiVersion())) {
			return MsgEmity.err(8006, "记录版本号错误");
		}
		
		if (recharge.getiState().intValue() < 0) {
			return MsgEmity.err(8007, "记录已经(标记)删除");
		}
		
		recharge.setiVersion(recharge.getiVersion() +1);
		recharge.setiState(0 - recharge.getiState());
		recharge.setsModifieder(sLoginUserId);
		recharge.setdModifiedDate(new Date());
		recharge.setsRecordKey(recharge.createRecordKey(recordKeyJam));
		
		return rechargeDao.signDel(recharge);
	}

	/**
	 * 移除删除标记
	 * @Param uId
	 * @Param iVersion
	 * @Param sRecordKey
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity removeSignDel(String uId, Integer iVersion, String sRecordKey) {
		if (null == uId || "".equals(uId.trim())) {
			return MsgEmity.err(8001, "记录编号缺失");
		}
		
		if (null == iVersion || iVersion.intValue() < 0) {
			return MsgEmity.err(8002, "记录版本号必须大于0");
		}
		
		if (null == sRecordKey || "".equals(sRecordKey.trim())) {
			return MsgEmity.err(8003, "记录验证密钥缺失");
		}
		
		MsgEmity me = rechargeDao.findById(uId);
		if (!me.isSuccess()) {
			return me;
		}
		
		String sLoginUserId = ModuleUtil.currentLoginUserId();
		
		Recharge recharge = me.getData();
		if (!sLoginUserId.equals(recharge.getsCreator()) && !"00000000/00000001".contains(sLoginUserId)) {
			return MsgEmity.err(8004, "当前用户无权删除此记录");
		}
		
		if (sRecordKey.equals(recharge.getsRecordKey())) {
			return MsgEmity.err(8005, "记录验证密钥错误");
		}
		
		if (iVersion.equals(recharge.getiVersion())) {
			return MsgEmity.err(8006, "记录版本号错误");
		}

		if (recharge.getiState().intValue() > 0) {
			return MsgEmity.err(8007, "记录已经移除删除标记");
		}
		
		recharge.setiVersion(recharge.getiVersion() +1);
		recharge.setiState(0 - recharge.getiState());
		recharge.setsModifieder(sLoginUserId);
		recharge.setdModifiedDate(new Date());
		recharge.setsRecordKey(recharge.createRecordKey(recordKeyJam));
		
		return rechargeDao.signDel(recharge);
	}
	
	/**
	 * 根据编号查询数据
	 * @Param uId
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findByPageRow(String uId) {
		if (null == uId || "".equals(uId.trim())) {
			return MsgEmity.err(8001, "记录编号缺失");
		}
		
		MsgEmity me = rechargeDao.findById(uId);
		if (!me.isSuccess()) {
			return me;
		}

		String sLoginUserId = ModuleUtil.currentLoginUserId();

		Recharge recharge = me.getData();
		if (!sLoginUserId.equals(recharge.getsCreator()) && !"00000000/00000001".contains(sLoginUserId)) {
			return MsgEmity.err(8002, "当前用户无权查看此记录");
		}
		
		return me;
	}
	
	/**
	 * 查询分页信息
	 * @param sStates
	 * @param pageCurrent
	 * @param pageSize
	 * @return
	 */
	@Override
	public MsgEmity findByPage(String sStates, Integer pageCurrent, Integer pageSize) {
		Integer[] iStates = IntegerUtil.strToInts(sStates, ";");
		if (null == iStates || iStates.length < 1) {
			return MsgEmity.err(8001, "状态条件缺失");
		}
			
		Page page = new Page(pageCurrent, pageSize);
		
		return rechargeDao.findByPage(iStates, page);
	}
	
	//----------------------- 同步充值金额到顾客账号 开始 ------------------------//
	
	private static boolean isBus = false;
	
	/**
	 * 同步线程
	 * Spring 启动完成后，会自动调用此方法
	 */
	@PostConstruct
	private void doThread() {
		new Thread(() -> {
			while(true) {
				try {
					if (isBus) {
						Thread.sleep(60000);
						continue;
					}
					
					isBus = true;
					changeCustomerAccount();
					Thread.sleep(60000);
					isBus = false;
				} catch (Exception e) {
					isBus = false;
				}
			}
		}).start();
	}
	
	/**
	 * 同步更新顾客账户中的余额与积分
	 * @return
	 */
	private void changeCustomerAccount() {
		MsgEmity me = rechargeDao.findByState(3);
		if (!me.isSuccess()) {
			return;
		}
		
		List<Recharge> list = me.getData();
		if (null == list || list.size() < 1) {
			return;
		}
		
		for (Recharge recharge : list) {
			me = changeCustomerAccount(recharge);
		}
	}
	
	/**
	 * 同步更新顾客账户中的余额与积分
	 * @return
	 */
	@Override
	public MsgEmity changeCustomerAccount(Recharge recharge) {
		if (recharge.getiErrorCount() > 5) {
			return MsgEmity.err(8001, "错误记录过多,不处理");//错误数量过多,不处理
		}
		
		if (!recharge.createRecordKey(recordKeyJam).equals(recharge.getsRecordKey())) {
			rechargeDao.addErrorCount(recharge.getuId());
		}
		
		MsgEmity me = rechargeDao.findCustomer(recharge.getsCustomerId());
		if (!me.isSuccess()) {
			return me;
		}
		
		CustomerAccountBase customerAccount = me.getData();
		if (!customerAccount.createRecordKey(recordKeyJam).equals(customerAccount.getsRecordKey())) {
			return me;//账号信息验证错误
		}
		
		Date now = new Date();
		
		recharge.setiState(4);
		recharge.setdModifiedDate(now);
		recharge.setiVersion(recharge.getiVersion() +1);
		recharge.setsRecordKey(recharge.createRecordKey(recordKeyJam));
		
		TallyBase tally = new TallyBase();
		tally.setuId(recharge.getuId());
		tally.setsCustomerId(recharge.getsCustomerId());
		tally.setiTally(recharge.getiTally());
		tally.setsMemo(null);
		tally.setsCreator(recharge.getsCreator());
		tally.setdCreateDate(now);
		tally.setsModifieder(recharge.getsModifieder());
		tally.setdModifiedDate(now);
		tally.setiState(1);
		tally.setiIndex(1);
		tally.setiVersion(1);
		tally.setsRecordKey(tally.createRecordKey(recordKeyJam));
		
		customerAccount.setmFund(MoneyUtil.addMoney(customerAccount.getmFund(), recharge.getmFund()));
		customerAccount.setiTally(customerAccount.getiTally() + recharge.getiTally());
		customerAccount.setdModifiedDate(now);
		customerAccount.setiVersion(customerAccount.getiVersion() +1);
		customerAccount.setsRecordKey(customerAccount.createRecordKey(recordKeyJam));
		
		rechargeDao.changeCustomerAccount(recharge, tally, customerAccount);
		
		return MsgEmity.success(8999, "执行成功");
	}
	
	//----------------------- 同步充值金额到顾客账号 结束 ------------------------//

}
